/**
 * Notes: 工作流模块业务逻辑
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2024-06-24 07:48:00 
 */

// 使用统一配置入口模式
const pathResolver = require('../../config/path_resolver.js');
const BaseBiz = require('./base_biz.js');
const projectSetting = require('../../config/projects.js');
const helpers = require('../../config/project_helpers_config');
const pageHelper = helpers.pageHelper;
const fileHelper = helpers.fileHelper;
const cloudHelper = helpers.cloudHelper;

// 修改为不使用继承的方式，直接创建FlowBiz对象
const FlowBiz = {
	// 合并BaseBiz的方法
	...BaseBiz,

	async openFlowFile(e, that) {
		let idx = pageHelper.dataset(e, 'idx');
		let node = that.data.flow.FLOW_OBJ.file[idx];
		return fileHelper.openFile(node);
	},

	// 分类菜单
	getCateMenu(name = '') {
		let sortItems = [{ label: name || '分类', type: 'cateId', value: '' }];

		let allSteps = projectSetting.FLOW_ALL_STEPS;
		for (let k = 0; k < allSteps.length; k++) {
			sortItems.push({ label: allSteps[k].FLOW_NAME, type: 'cateId', value: allSteps[k].FLOW_CATE_ID });
		}

		return sortItems;
	},

	async loadDetail(that) {
		if (!that || typeof that.setData !== 'function') {
			console.error('参数错误：that对象无效');
			return;
		}

		let id = that.data.id;
		console.log('开始加载流程详情，原始ID:', id);

		// ID格式验证和处理
		if (typeof id === 'object' && id._id) {
			id = id._id;
			console.log('ID是对象格式，提取后:', id);
		}

		if (!id) {
			console.error('流程ID为空');
			that.setData({
				isLoad: true,
				flow: null
			});
			pageHelper.showModal('未找到流程ID');
			return;
		}

		// 先显示加载中
		that.setData({
			isLoad: false
		});

		try {
			console.log('准备调用云函数，ID:', id);
			let flow = await cloudHelper.callCloudData('flow/view', { id });
			
			if (!flow) {
				console.error('未找到流程数据');
				that.setData({
					isLoad: true,
					flow: null
				});
				pageHelper.showModal('未找到流程数据');
				return;
			}

			console.log('获取到流程数据:', flow);

			// 验证必要的字段
			if (!flow.FLOW_CATE_ID) {
				console.error('流程数据缺少分类ID');
				that.setData({
					isLoad: true,
					flow: null
				});
				pageHelper.showModal('流程数据不完整');
				return;
			}

			// 查找对应的步骤
			let curStep = null;
			try {
				let allSteps = projectSetting.FLOW_ALL_STEPS;
				
				// 通过FLOW_CATE_ID匹配
				for (let k = 0; k < allSteps.length; k++) {
					if (allSteps[k].FLOW_CATE_ID == flow.FLOW_CATE_ID) {
						curStep = allSteps[k];
						console.log('匹配到步骤:', curStep.FLOW_NAME);
						break;
					}
				}
				
				// 如果没找到，尝试通过名称匹配
				if (!curStep && flow.FLOW_CATE_NAME) {
					for (let k = 0; k < allSteps.length; k++) {
						if (allSteps[k].FLOW_NAME == flow.FLOW_CATE_NAME) {
							curStep = allSteps[k];
							console.log('通过名称匹配到步骤:', curStep.FLOW_NAME);
							break;
						}
					}
				}
				
				// 如果还是没找到，使用第一个
				if (!curStep && allSteps.length > 0) {
					curStep = allSteps[0];
					console.log('使用默认步骤:', curStep.FLOW_NAME);
				}
			} catch (err) {
				console.error('获取流程步骤失败:', err);
			}

			// 获取表单字段
			let fields = null;
			if (curStep && curStep.FLOW_FIELDS) {
				fields = curStep.FLOW_FIELDS;
				console.log('从步骤获取到字段:', fields.length);
			} else if (flow.FLOW_FORMS) {
				// 从现有表单反向构建字段
				fields = [];
				let forms = flow.FLOW_FORMS;
				for (let i = 0; i < forms.length; i++) {
					fields.push({
						mark: forms[i].mark,
						title: forms[i].title,
						type: forms[i].type,
						must: false
					});
				}
				console.log('从表单构建出字段:', fields.length);
			}

			// 更新页面数据
			that.setData({
				flow,
				curStep,
				fields,
				isLoad: true
			});

			// 更新导航栏标题
			if (curStep) {
				wx.setNavigationBarTitle({
					title: '申请单修改 - ' + curStep.FLOW_NAME
				});
			}

		} catch (err) {
			console.error('加载流程详情失败:', err);
			that.setData({
				isLoad: true,
				flow: null
			});
			pageHelper.showModal(err.message || '加载失败，请重试');
		}
	},

	// 创建一个虚拟的flow对象用于调试
	_createDummyFlow(options) {
		try {
			let cateId = options.cateId;
			if (!cateId) return null;
			
			let allSteps = projectSetting.FLOW_ALL_STEPS;
			let cateName = '';
			
			for (let k = 0; k < allSteps.length; k++) {
				if (allSteps[k].FLOW_CATE_ID == cateId) {
					cateName = allSteps[k].FLOW_NAME;
					break;
				}
			}
			
			return {
				_id: 'dummy_' + cateId,
				FLOW_CATE_ID: cateId,
				FLOW_CATE_NAME: cateName,
				FLOW_FORMS: [],
				FLOW_OBJ: {
					title: cateName + '申请',
					person: '',
					phone: ''
				},
				IS_DUMMY: true // 标记为虚拟数据
			};
		} catch (err) {
			console.error('创建虚拟流程数据出错:', err);
			return null;
		}
	},

	initFormData(id = '', cateId) {
		let fields = null;
		let allSteps = projectSetting.FLOW_ALL_STEPS;
		for (let k = 0; k < allSteps.length; k++) {
			if (allSteps[k].FLOW_CATE_ID == cateId) {
				fields = allSteps[k].FLOW_FIELDS;
				break;
			}
		}
		return {
			id,
			fields
		}
	},

	initFormStepData(id = '') {
		return {
			id,
			fields: projectSetting.FLOW_SETP_FIELDS
		}
	},

	async delFlow(id, callback) {
		let cb = async () => {
			try {
				let params = {
					id
				}
				let opts = {
					title: '删除中'
				}

				await cloudHelper.callCloudSumbit('flow/del', params, opts).then(res => {
					pageHelper.showSuccToast('删除成功', 1500, callback);
				});
			} catch (err) {
				console.log(err);
			}
		}

		pageHelper.showConfirm('确认删除? 删除不可恢复', cb);
	}
};

// 添加CHECK_FORM属性
FlowBiz.CHECK_FORM = {
	forms: 'formForms|array',
};

module.exports = FlowBiz;